package com.zhan.ielts.web.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.ielts.service.DynamicCodeService;
import com.zhan.ielts.utils.Contents;
import com.zhan.ielts.utils.SendSMSSelf;

@Controller
@RequestMapping("/dynamic/code")
public class DynamicCodeController {

	private Logger log = LoggerFactory.getLogger(DynamicCodeController.class);

	@Autowired
	private DynamicCodeService dynamicCodeService;

	@ResponseBody
	@RequestMapping(value = "/send", method = RequestMethod.POST)
	public CustomResult send(String mobile) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		if (StringUtils.isEmpty(mobile)) {
			log.error("手机号为空！");
			map.put("errCode", 1001);
			return new CustomResult(0, "手机号为空！", map);
		}

		try {
			Long count = dynamicCodeService.verifyBeforeGenerate(mobile);
			if (count > 0) {
				map.put("errCode", 1002);
				return new CustomResult(0, "短信发送时间间隔小于45秒", map);
			} 
			
			String code = dynamicCodeService.generateDynamicCode();
			log.debug("动态码" + code);
			boolean flag = SendSMSSelf.sendSMS(mobile, code, Contents.SMS_TOKEN_SELF);
			if (!flag) {
				log.debug("短信发送失败！");
				map.put("errCode", 1003);
				return new CustomResult(0, "短信发送失败！", map);
			}
			dynamicCodeService.saveDynamicCode(mobile, code);

		} catch (Exception e) {
			log.debug("系统错误！");
			map.put("errCode", 1004);
			return new CustomResult(0, "系统错误！", map);
		}

		log.debug("短信发送成功！");
		return new CustomResult(1, "短信发送成功", "");

	}

	@ResponseBody
	@RequestMapping(value = "/verify", method = RequestMethod.POST)
	public CustomResult verify(String mobile, String code) {
		log.debug("验证动态码开始");
		Map<String, Integer> map = new HashMap<String, Integer>();

		if (StringUtils.isEmpty(mobile)) {
			log.error("手机号码为空！");
			map.put("errCode", 1001);
				return new CustomResult(0, "手机号码为空！", map);
		} else if (StringUtils.isEmpty(code)) {
			log.error("动态码为空！");
			map.put("errCode", 1002);
			return new CustomResult(0, "动态码为空！", map);
		}

		try {
			Long count = dynamicCodeService.verifyDynamicCode(mobile, code);
			if (count > 0) {
				return new CustomResult(1, "", "");
			} else {
				log.error("动态码错误或无效！");
				map.put("errCode", 1003);
				return new CustomResult(0, "动态码错误或无效！", map);
			}

		} catch (Exception e) {
			log.error("系统错误！");
			map.put("errCode", 1004);
			return new CustomResult(0, "系统错误！", map);
		}

	}

}
